<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first">
            <!-- 按钮 -->
            <el-button icon="el-icon-plus" size="small" type="primary" class="addBtn" @click="showDialog=true">新增角色</el-button>
            <!-- 表格 -->
            <el-table :data="roleList" stripe border class="Table">
              <el-table-column type="index" label="序号" width="120" :index="indexMethod" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template v-slot="{row}">
                  <el-button size="small" type="success" @click="assignpermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="edit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              :current-page="page"
              :page-sizes="[2, 3, 5, 10]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="second">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 新增与编辑角色的弹出框 -->
      <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="clickSubmit">确认</el-button>
        </template>
      </el-dialog>

      <!-- 分配权限的弹出框 -->
      <el-dialog title="分配权限" :visible="showDialogPermission" @close="handlePermissionClose" @open="handlePermissionOpen">
        <el-tree
          ref="tree"
          v-loading="loading"
          :data="permissionData"
          :props="{ label: 'name' }"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />
        内容部分
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="handlePermissionClose">取消</el-button>
            <el-button type="primary" @click="clickPermissionSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqDelRole, reqAddRole, reqGetRoleDetail, reqUpdateRole, reqGetCompanyById, reqAssignPerm } from '@/api/setting'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permisson'
import { transListToTree } from '@/utils/index'

export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'roles',
      page: 1,
      pagesize: 3,
      roleList: [],
      total: 0,
      /* 控制弹出框的显示与隐藏 */
      showDialog: false,
      companyForm: {},
      showDialogPermission: false,
      permissionData: [], // 存储权限数据,
      roleId: '',
      loading: false,

      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      }

    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 分配权限
    assignpermission(id) {
      this.showDialogPermission = true
      this.roleId = id
    },
    // 权限弹出框关闭
    handlePermissionClose() {
      this.showDialogPermission = false
      this.$refs.tree.setCheckedKeys([])
    },
    // // 获取权限列表
    // async getPermissionOpen() {
    //   const { data } = await reqGetPermissionList()
    //   this.permissionData = transListToTree(data, '0')
    // },

    // 点击权限弹出框显示数据
    async handlePermissionOpen() {
      this.loading = true
      const { data } = await reqGetPermissionList()
      this.permissionData = transListToTree(data, '0')
      // 根据id获取当前权限
      const { data: { permIds }} = await reqGetRoleDetail(this.roleId)
      this.$refs.tree.setCheckedKeys(permIds)
      this.loading = false
    },
    // 点击确定更新分配权限
    async clickPermissionSubmit() {
      await reqAssignPerm({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })

      this.$message.success('更新权限成功')
      this.handlePermissionClose()
    },

    async getRoleList() {
      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      this.roleList = rows
      this.total = total
    },
    handleSizeChange(newSize) {
      this.pagesize = newSize
      this.getRoleList()
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getRoleList()
    },
    // 自定义索引值
    // 需求:让数据按照顺序排列
    // 算法: (page-1)* pagesize + index +1
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 点击删除
    async  delRole(id) {
      const res = await this.$confirm('确定要永久删除吗', '提示').catch(err => err)
      if (res === 'cancel') return

      await reqDelRole(id)
      // 成功提示
      this.$message.success('删除成功')

      // 解决删除时候只有一条数据的小bug
      if (this.roleList.length === 1 && this.page > 1) {
        this.page--
      }

      // 刷新数据
      this.getRoleList()
    },
    // 关闭弹出框
    closeDialog() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      // 清空数据
      this.form = { name: '', description: '' }
    },
    // 点击确认添加
    clickSubmit() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return

        if (this.form.id) {
          // 编辑
          await reqUpdateRole(this.form)
          this.$message.success('更新角色成功')
        } else {
          await reqAddRole(this.form)
          // 成功提示
          this.$message.success('添加角色成功')
        }

        // 关闭弹窗
        this.closeDialog()
        // 刷新页面
        this.getRoleList()
      })
    },
    // 点击编辑
    async edit(id) {
      const { data: res } = await reqGetRoleDetail(id)
      this.form = res
      this.showDialog = true
    },
    // 获取公司信息
    async getCompanyInfo() {
      const { data: res } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = res
    }
  }
}
</script>

<style lang="scss" scoped>
.Table{
  margin: 15px 0;
}
</style>>

